package com.breaktian.assemble.socket.udt;

import com.breaktian.assemble.socket.callback.DataReceive;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;

import udt.UDTInputStream;
import udt.UDTReceiver;
import udt.UDTServerSocket;
import udt.UDTSocket;


/**
 * @author breaktian
 * udt协议
 * udt服务端
 * */
public class UdtServerSocket {
	
	private UDTServerSocket udtServerSocket;

	/**
	 * 指定监听的端口号
	 * */
	public UdtServerSocket(int port){
		try {
			UDTReceiver.dropRate = 0;
			udtServerSocket=new udt.UDTServerSocket(port);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
	
	
	
	
	/**
	 * 监听消息
	 * */
	public void listen(DataReceive call){
		if(udtServerSocket==null) throw new IllegalStateException("udtServerSocket为null");
		UDTSocket s = null;
		try {
			s = udtServerSocket.accept();
			UDTInputStream is=s.getInputStream();
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			DataInputStream dis = new DataInputStream(is);
			byte[] buf = new byte[1024];
			while(true){
				int c=dis.read(buf);
				if(c<0)break;
				else{
					bos.write(buf, 0, c);
				}
			}
			byte receiveData[] = bos.toByteArray();
			call.onReceive(receiveData);
			s.close();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 关闭服务端
	 * */
	public void shutDown(){
		if(udtServerSocket==null) throw new IllegalStateException("udtServerSocket为null");
		udtServerSocket.shutDown();
	}
	
	
}
